package com.wHitE.servlet;

import com.google.gson.Gson;
import com.wHitE.pojo.Book;
import com.wHitE.utils.Result;
import com.wHitE.service.AddBookService;
import com.wHitE.service.impl.AddBookServiceImpl;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/addBook")
public class AddBookServlet extends HttpServlet {
    private AddBookService addBookService = new AddBookServiceImpl();

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("新增书籍信息接口初始化...");
        super.init(config);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("新增书籍信息接口调用...");
        super.service(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取out对象
        PrintWriter out = resp.getWriter();

        //获取全部参数map
        //        Map<String, String[]> parameterMap = req.getParameterMap();
        //        Set<String> keySet = parameterMap.keySet();
        //        for (String key : keySet) {
        //            String[] values = parameterMap.get(key);
        //            System.out.println(key + ":");
        //            for (String value : values) {
        //                System.out.println(value + " ");
        //            }
        //        }

        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String quantity = req.getParameter("quantity");
        String coverImg = req.getParameter("coverImg");
        String author = req.getParameter("author");
        String uploader = req.getParameter("uploader");

        // 初始化 object=>json 对象
        Gson gson = new Gson();

        //数据流获取信息
        StringBuilder stringBuilder = new StringBuilder();// 可变字符串构造对象
        BufferedReader reader = req.getReader();// 字符流读取对象
        char[] buf = new char[1024];// 创建字符数组(长度为请求体大小)
        int len;
        while ((len = reader.read(buf)) != -1) {// 追加字符串
            stringBuilder.append(buf, 0, len);
        }
        // 关闭字符输入流
        reader.close();
        // 将可变字符串转为字符串
        String str = stringBuilder.toString();

        String msg;

        if (name == null && price == null && quantity == null
                && coverImg == null && author == null && uploader == null) {
            if (!str.isEmpty()) {
                //                // 以下方式通过解析json字符串,获取参数值并转换为需要的数据类型
                //                // 实例化json解析对象
                //                JsonParser parser = new JsonParser();
                //                // 实例化json对象元素
                //                JsonElement element = parser.parse(str);
                try {
                    //                    // 获取并转换为所需的数据类型
                    //                    name = element.getAsJsonObject().get("name").getAsString();
                    //                    price = element.getAsJsonObject().get("price").getAsString();
                    //                    quantity = element.getAsJsonObject().get("quantity").getAsString();
                    //                    coverImg = element.getAsJsonObject().get("coverImg").getAsString();
                    //                    author = element.getAsJsonObject().get("author").getAsString();
                    //                    uploader = element.getAsJsonObject().get("uploader").getAsString();
                    // 以下方式通过创建类(属性与json对象的键值对应)接收请求的data参数值
                    // 第一个参数需要json对象,第二个参数是对应的类
                    Book book = gson.fromJson(str, Book.class);
                    msg = addBookService.addBook(book.getName(), book.getPrice(), book.getQuantity(), book.getCoverImg(), book.getAuthor(),
                            book.getUploader());
                } catch (Exception e) {
                    out.print(gson.toJson(Result.error("请求体参数错误")));
                    return;
                }
            } else {
                out.print(gson.toJson(Result.error("路径参数错误")));
                return;
            }
        } else {
            msg = addBookService.addBook(name, Double.parseDouble(price), Integer.parseInt(quantity), coverImg, author, uploader);
        }

        // 判断是否请求成功...并响应给前端
        if (msg.equals("success")) {
            out.print(gson.toJson(Result.success()));
        } else {
            out.print(gson.toJson(Result.error(msg)));
        }
    }

    @Override
    public void destroy() {
        System.out.println("新增书籍信息接口关闭...");
    }
}
